<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class products extends CI_Controller {

    protected $_templates;

    function __construct() {
        parent::__construct();
        $this->pre_message = "";
        $this->session->set_userdata(array('Url' => uri_string()));
        $this->load->library('string_library');
        $this->load->library('image_library');
        $this->load->helper('upload_file');
        $this->load->model('products_model', 'products');
        $this->load->model('partners_model', 'partners');
        $this->load->model('size_model', 'size');
        $this->load->model('color_model', 'color');
        $this->load->model('material_model', 'material');
        $this->load->model('product_category_model', 'product_category');
    }

    function index() {
        $this->acl->check('view', 'mod_products', 'products', base_url());
        $this->listproducts();
    }

    function listproducts($action = '') {
        // check quyền xem
        $this->acl->check('view', 'mod_products', 'products', base_url());
        /* Begin search */
        $type = $this->input->post('type');
        $data['option_pid'] = $this->product_category->optionCategoryLevel();
        $data['partners_id'] = $this->partners->optionCategoryLevel();
        if ($_POST) {
            $name = $this->input->post('name');
            $data['name'] = $name;
            $sku = $this->input->post('sku');
            $data['sku'] = $sku;
            $conhang = $this->input->post('conhang');
            $data['conhang'] = $conhang;
            $product_category_id = $this->input->post('product_category_id');
            $partners_id = $this->input->post('partners_id');
            $data['option_pid'] = $this->product_category->optionCategoryLevel(0, $product_category_id);
            $data['partners_id'] = $this->partners->optionCategoryLevel($partners_id);
            $data['arr_search'] = array('name' => $name, 'product_category_id' => $product_category_id, 'partners_id' => $partners_id, 'sku' => $sku, 'conhang' => $conhang);
        } else
            $data['arr_search'] = '';
        $data['title'] = 'Danh sách sản phẩm';
        if ($this->acl->check('add', 'mod_products', 'products'))
            $data['add'] = 'products/add';
        //if($this->acl->check('export','mod_products','products'))
        //$data['export'] = 'products/export';
        $config['base_url'] = base_url() . 'products/listproducts/' . (int) $this->uri->segment(3);
        $data['num'] = $this->products->get_num_data($data['arr_search']);
        $config['total_rows'] = $data['num'];
        $config['per_page'] = '20';
        $config['uri_segment'] = 4;
        $this->pagination->initialize($config);
        $data['list'] = $this->products->get_all_data($config['per_page'], (int) $this->uri->segment('4'), $data['arr_search']);
        $data['pagination'] = $this->pagination->create_links();

        $this->_templates['page'] = 'products/listproducts';
        if ($type == "ajax")
            echo $this->load->view($this->_templates['page'], $data, true);
        else
            $this->site_lib->load($this->_templates['page'], $data);
    }

    function listsale($action = '') {
        // check quyền xem
        $this->acl->check('view', 'mod_products', 'products', base_url());
        /* Begin search */
        $type = $this->input->post('type');
        $data['option_pid'] = $this->product_category->optionCategoryLevel();
        $data['partners_id'] = $this->partners->optionCategoryLevel();
        if ($_POST) {
            $name = $this->input->post('name');
            $data['name'] = $name;
            $sku = $this->input->post('sku');
            $data['sku'] = $sku;
            $conhang = $this->input->post('conhang');
            $data['conhang'] = $conhang;
            $product_category_id = $this->input->post('product_category_id');
            $partners_id = $this->input->post('partners_id');
            $data['option_pid'] = $this->product_category->optionCategoryLevel(0, $product_category_id);
            $data['partners_id'] = $this->partners->optionCategoryLevel($partners_id);
            $data['arr_search'] = array('name' => $name, 'product_category_id' => $product_category_id, 'partners_id' => $partners_id, 'sku' => $sku, 'conhang' => $conhang);
        } else
            $data['arr_search'] = '';
        $data['title'] = 'Danh sách sản phẩm khuyến mãi';
        if ($this->acl->check('add', 'mod_products', 'products'))
            $data['add'] = 'products/add';
        if ($this->acl->check('export', 'mod_products', 'products'))
        //$data['export'] = 'products/export';
            $config['base_url'] = base_url() . 'products/listsale/' . (int) $this->uri->segment(3);
        $data['num'] = $this->products->get_num_sale($data['arr_search']);
        $config['total_rows'] = $data['num'];
        $config['per_page'] = '20';
        $config['uri_segment'] = 4;
        $this->pagination->initialize($config);
        $data['list'] = $this->products->get_all_sale($config['per_page'], (int) $this->uri->segment('4'), $data['arr_search']);
        $data['pagination'] = $this->pagination->create_links();
        $this->_templates['page'] = 'products/listsale';
        if ($type == "ajax")
            echo $this->load->view($this->_templates['page'], $data, true);
        else
            $this->site_lib->load($this->_templates['page'], $data);
    }

    function add() {
        // check quyền thêm
        $this->acl->check('add', 'mod_products', 'products', base_url());
        $data['title'] = 'Thêm mới sản phẩm';
        $data['materialItems'] = $this->material->getAllData();
        $data['colorItems'] = $this->color->getAllData();
        $data['sizeItems'] = $this->size->getAllData();
        $data['option_pid'] = $this->product_category->optionCategoryLevel();
//        $data['partners_pid'] = $this->partners->optionCategoryLevel();
        $this->form_validation->set_rules('product_category_id', "Danh mục sản phẩm", 'trim|required');
//        $this->form_validation->set_rules('partners_id', 'Thương hiệu', 'trim|required');
//        $this->form_validation->set_rules('code', "Mã sản phẩm", 'trim|required');
        $this->form_validation->set_rules('name', "Tên sản phẩm", 'trim|required');
        $this->form_validation->set_rules('price', 'Giá bán', 'trim|required');
        $this->form_validation->set_rules('image', 'Hình ảnh', 'trim|required');
        $this->form_validation->set_rules('details', 'Chi tiết sản phẩm', 'trim|required');
        if ($this->form_validation->run()) {
            //đường dẫn hình ảnh
            $dirFile = "../uploads/images/";
            $dirFileAvatar = "../uploads/products/avatar/";
            $dirFileMedium = "../uploads/products/medium/";
            $filename = $_POST['image'];
            $dirFileRoot = $dirFile . $filename;
            $dirFileResizeSmall = $dirFileAvatar . $filename;
            $dirFileResizeMedium = $dirFileMedium . $filename;
            if (file_exists($dirFileResizeSmall)) {
                $img_name = $this->image_library->resizeThumbnailImage($dirFileResizeSmall, $dirFileRoot, 212, 248, 0, 0, 0);
            }
            if (file_exists($dirFileResizeMedium)) {
                $img_name = $this->image_library->resizeThumbnailImage($dirFileResizeMedium, $dirFileRoot, 400, 400, 0, 0, 0);
            }
            $filename == $filename;
            $arr_image = array('image' => $filename);
            // upload các hình ảnh khác 
            if ($_POST['image_1'] != '') {
                $filename_1 = $_POST['image_1'];
                $dirFileRoot_1 = $dirFile . $filename_1;
                $dirFileResizeSmall_1 = $dirFileAvatar . $filename_1;
                $dirFileResizeMedium_1 = $dirFileMedium . $filename_1;
                $img_name1 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_1, $dirFileRoot_1, 400, 400, 0, 0, 0);
                $img_name_1 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_1, $dirFileRoot_1, 1200, 1000, 0, 0, 0);
                $arr_image1 = array('image_1' => $filename_1);
            } else {
                $arr_image1 = array('image_1' => '');
            }

            if ($_POST['image_2'] != '') {
                $filename_2 = $_POST['image_2'];
                $dirFileRoot_2 = $dirFile . $filename_2;
                $dirFileResizeSmall_2 = $dirFileAvatar . $filename_2;
                $dirFileResizeMedium_2 = $dirFileMedium . $filename_2;
                $img_name2 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_2, $dirFileRoot_2, 400, 400, 0, 0, 0);
                $img_name_2 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_2, $dirFileRoot_2, 1200, 1000, 0, 0, 0);
                $arr_image2 = array('image_2' => $filename_2);
            } else {
                $arr_image2 = array('image_2' => '');
            }
            if ($_POST['image_3'] != '') {
                $filename_3 = $_POST['image_3'];
                $dirFileRoot_3 = $dirFile . $filename_3;
                $dirFileResizeSmall_3 = $dirFileAvatar . $filename_3;
                $dirFileResizeMedium_3 = $dirFileMedium . $filename_3;
                $img_name_3 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_3, $dirFileRoot_3, 400, 400, 0, 0, 0);
                $img_name_3 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_3, $dirFileRoot_3, 1200, 1000, 0, 0, 0);
                $arr_image3 = array('image_3' => $filename_3);
            } else {
                $arr_image3 = array('image_3' => '');
            }
            if ($_POST['image_4'] != '') {
                $filename_4 = $_POST['image_4'];
                $dirFileRoot_4 = $dirFile . $filename_4;
                $dirFileResizeSmall_4 = $dirFileAvatar . $filename_4;
                $dirFileResizeMedium_4 = $dirFileMedium . $filename_4;
                $img_name_4 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_4, $dirFileRoot_4, 400, 400, 0, 0, 0);
                $img_name_4 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_4, $dirFileRoot_4, 1200, 1000, 0, 0, 0);
                $arr_image4 = array('image_4' => $filename_4);
            } else {
                $arr_image4 = array('image_4' => '');
            }
            if ($_POST['image_5'] != '') {
                $filename_5 = $_POST['image_5'];
                $dirFileRoot_5 = $dirFile . $filename_5;
                $dirFileResizeSmall_5 = $dirFileAvatar . $filename_5;
                $dirFileResizeMedium_5 = $dirFileMedium . $filename_5;
                $img_name_5 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_5, $dirFileRoot_5, 400, 400, 0, 0, 0);
                $img_name_5 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_5, $dirFileRoot_5, 1200, 1000, 0, 0, 0);
                $arr_image5 = array('image_5' => $filename_5);
            } else {
                $arr_image5 = array('image_5' => '');
            }
            // lưu alias các cấp danh mục sản phẩm
            $product_category_id = $this->input->post('product_category_id');
            $procate_name_alias = $this->product_category->getAlias($product_category_id);
            $name_alias = $procate_name_alias . '/' . $this->string_library->stringchange($this->input->post('name'));
            $arr_alias = array('name_alias' => $name_alias);
            // get các thuộc tính của sản phẩm 
            $arr_material_check = $this->input->post('arr_material');
            $arr_size_check = $this->input->post('arr_size');
            $arr_color_check = $this->input->post('arr_color');
            // get các field 
            $data = $this->build_data($_POST, 1);
            $data = array_merge($data, $arr_alias);
            $data = array_merge($data, $arr_image);
            $data = array_merge($data, $arr_image1);
            $data = array_merge($data, $arr_image2);
            $data = array_merge($data, $arr_image3);
            $data = array_merge($data, $arr_image4);
            $data = array_merge($data, $arr_image5);
            $insert_product_id = $this->products->saveData(0, $data);
            if ($insert_product_id) {
                // chất liệu
                if ($arr_material_check) {
                    foreach ($arr_material_check as $material_item) {
                        $material_save = array('product_id' => $insert_product_id, 'material_id' => $material_item);
                        $this->material->saveProductData(0, $material_save);
                    }
                }
                // lưu kích thước
                if ($arr_size_check) {
                    foreach ($arr_size_check as $size_item) {
                        $size_save = array('product_id' => $insert_product_id, 'size_id' => $size_item);
                        $this->size->saveProductData(0, $size_save);
                    }
                }
                // màu sắc
                if ($arr_color_check) {
                    foreach ($arr_color_check as $color_item) {
                        $color_save = array('product_id' => $insert_product_id, 'color_id' => $color_item);
                        $this->color->saveProductData(0, $color_save);
                    }
                }
                $this->session->set_flashdata('message', 'Lưu thành công');
                redirect('products/listproducts');
            } else {
                $this->pre_message = 'Lưu không thành công';
            }
        } else if (!empty($_POST)) {

            $this->pre_message = validation_errors();
        }
        $data['message'] = $this->pre_message;
        $this->_templates['page'] = 'products/add';
        $this->site_lib->load($this->_templates['page'], $data);
    }

    function edit($id) {
        // check quyền thêm 
        $this->acl->check('edit', 'mod_products', 'products', base_url());
        $data['title'] = 'Sửa bài viết';
        $data['item'] = $this->products->get_object($id);
        $data['partners_pid'] = $this->partners->optionCategoryLevel($data['item']->partners_id);
        $data['materialItems'] = $this->material->getAllData();
        $data['colorItems'] = $this->color->getAllData();
        $data['sizeItems'] = $this->size->getAllData();
        $data['material_check'] = $this->material->get_object_from_product($id);
        $data['color_check'] = $this->color->get_object_from_product($id);
        $data['size_check'] = $this->size->get_object_from_product($id);
        $data['option_pid'] = $this->product_category->optionCategoryLevel(0, $data['item']->product_category_id);
        $this->form_validation->set_rules('product_category_id', "Danh mục sản phẩm", 'trim|required');
        $this->form_validation->set_rules('name', "Tên sản phẩm", 'trim|required');
        $this->form_validation->set_rules('price', 'Giá gốc', 'trim|required');
        $this->form_validation->set_rules('details', 'Chi tiết sản phẩm', 'trim|required');
        if ($this->form_validation->run() == FALSE) {
            $this->pre_message .= validation_errors();
        } else {
            $dirFile = "../uploads/images/";
            $dirFileAvatar = "../uploads/products/avatar/";
            $dirFileMedium = "../uploads/products/medium/";
            $filename = $_POST['image'];
            $dirFileRoot = $dirFile . $filename;
            $dirFileResizeSmall = $dirFileAvatar . $filename;
            $dirFileResizeMedium = $dirFileMedium . $filename;
            if ($_POST['image'] != '') {
                $img_name = $this->image_library->resizeThumbnailImage($dirFileResizeSmall, $dirFileRoot, 212, 248, 0, 0, 0);
                $img_name = $this->image_library->resizeThumbnailImage($dirFileResizeMedium, $dirFileRoot, 400, 400, 0, 0, 0);
                $filename = $filename;
            } else {
                $filename = $data['item']->image;
            }

            $arr_image = array('image' => $filename);

            // upload các hình ảnh khác 
            if ($_POST['image_1']) {
                $filename_1 = $_POST['image_1'];
                $dirFileRoot_1 = $dirFile . $filename_1;
                $dirFileResizeSmall_1 = $dirFileAvatar . $filename_1;
                $dirFileResizeMedium_1 = $dirFileMedium . $filename_1;
                $img_name1 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_1, $dirFileRoot_1, 400, 400, 0, 0, 0);
                $img_name_1 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_1, $dirFileRoot_1, 1200, 1000, 0, 0, 0);
                $arr_image1 = array('image_1' => $filename_1);
            } else {
                $arr_image1 = array('image_1' => $data['item']->image_1);
            }

            if ($_POST['image_2']) {
                $filename_2 = $_POST['image_2'];
                $dirFileRoot_2 = $dirFile . $filename_2;
                $dirFileResizeSmall_2 = $dirFileAvatar . $filename_2;
                $dirFileResizeMedium_2 = $dirFileMedium . $filename_2;
                $img_name2 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_2, $dirFileRoot_2, 400, 400, 0, 0, 0);
                $img_name_2 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_2, $dirFileRoot_2, 12000, 1000, 0, 0, 0);
                $arr_image2 = array('image_2' => $filename_2);
            } else {
                $arr_image2 = array('image_2' => $data['item']->image_2);
            }
            if ($_POST['image_3']) {
                $filename_3 = $_POST['image_3'];
                $dirFileRoot_3 = $dirFile . $filename_3;
                $dirFileResizeSmall_3 = $dirFileAvatar . $filename_3;
                $dirFileResizeMedium_3 = $dirFileMedium . $filename_3;
                $img_name_3 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_3, $dirFileRoot_3, 400, 400, 0, 0, 0);
                $img_name_3 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_3, $dirFileRoot_3, 12000, 1000, 0, 0, 0);
                $arr_image3 = array('image_3' => $filename_3);
            } else {
                $arr_image3 = array('image_3' => $data['item']->image_3);
            }

            if ($_POST['image_4']) {
                $filename_4 = $_POST['image_4'];
                $dirFileRoot_4 = $dirFile . $filename_4;
                $dirFileResizeSmall_4 = $dirFileAvatar . $filename_4;
                $dirFileResizeMedium_4 = $dirFileMedium . $filename_4;
                $img_name_4 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_4, $dirFileRoot_4, 400, 400, 0, 0, 0);
                $img_name_4 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_4, $dirFileRoot_4, 12000, 1000, 0, 0, 0);
                $arr_image4 = array('image_4' => $filename_4);
            } else {
                $arr_image4 = array('image_4' => $data['item']->image_4);
            }
            if ($_POST['image_5']) {
                $filename_5 = $_POST['image_5'];
                $dirFileRoot_5 = $dirFile . $filename_5;
                $dirFileResizeSmall_5 = $dirFileAvatar . $filename_5;
                $dirFileResizeMedium_5 = $dirFileMedium . $filename_5;
                $img_name_5 = $this->image_library->resizeThumbnailImage($dirFileResizeSmall_5, $dirFileRoot_5, 400, 400, 0, 0, 0);
                $img_name_5 = $this->image_library->resizeThumbnailImage($dirFileResizeMedium_5, $dirFileRoot_5, 12000, 1000, 0, 0, 0);
                $arr_image5 = array('image_5' => $filename_5);
            } else {
                $arr_image5 = array('image_5' => $data['item']->image_5);
            }
            // lưu alias các cấp danh mục sản phẩm
            $product_category_id = $this->input->post('product_category_id');
            $procate_name_alias = $this->product_category->getAlias($product_category_id);
            $name_alias = $procate_name_alias . '/' . $this->string_library->stringchange($this->input->post('name'));
            $arr_alias = array('name_alias' => $name_alias);
            // get các thuộc tính của sản phẩm 
            $arr_material_check = $this->input->post('arr_material');
            $arr_size_check = $this->input->post('arr_size');
            $arr_color_check = $this->input->post('arr_color');

            $data = $this->build_data($_POST, 1);
            $data = array_merge($data, $arr_alias);
            $data = array_merge($data, $arr_image);
            $data = array_merge($data, $arr_image1);
            $data = array_merge($data, $arr_image2);
            $data = array_merge($data, $arr_image3);
            $data = array_merge($data, $arr_image4);
            $data = array_merge($data, $arr_image5);
            if ($this->products->saveData($id, $data)) {
                // chất liệu
                $this->material->delete_pro($id);
                if ($arr_material_check) {
                    foreach ($arr_material_check as $material_item) {
                        $material_save = array('product_id' => $id, 'material_id' => $material_item);
                        $this->material->saveProductData(0, $material_save);
                    }
                }
                $this->size->delete_pro($id);
                // lưu kích thước
                if ($arr_size_check) {
                    foreach ($arr_size_check as $size_item) {
                        $size_save = array('product_id' => $id, 'size_id' => $size_item);
                        $this->size->saveProductData(0, $size_save);
                    }
                }
                // màu sắc
                $this->color->delete_pro($id);
                if ($arr_color_check) {
                    foreach ($arr_color_check as $color_item) {
                        $color_save = array('product_id' => $id, 'color_id' => $color_item);
                        $this->color->saveProductData(0, $color_save);
                    }
                }
                $this->session->set_flashdata('message', 'Lưu thành công');
                redirect('products/listproducts');
            } else {
                $this->pre_message = 'Lưu không thành công';
            }
        }
        $data['message'] = $this->pre_message;
        $this->_templates['page'] = 'products/edit';
        $this->site_lib->load($this->_templates['page'], $data);
    }

    function del() {
        // check quyền xóa
        $this->acl->check('del', 'mod_products', 'products', base_url());
        $id = $this->uri->segment(3);
        $page = $this->uri->segment(4);

        if ($this->products->deleted($id))
            $this->session->set_flashdata('message', 'Đã xóa thành công');
        else
            $this->session->set_flashdata('message', 'Xóa không thành công');

        redirect('products/listproducts/' . $page);
    }

    function dels() {
        // check quyền xóa nhiều 
        $this->acl->check('dels', 'mod_products', 'products', base_url());
        if (!empty($_POST['ar_id'])) {
            $page = (int) $this->input->post('page');
            $ar_id = $this->input->post('ar_id');

            if (!empty($_POST['btn_submit'])) {
                for ($i = 0; $i < sizeof($ar_id); $i ++) {
                    if ($ar_id[$i]) {
                        if ($this->products->deleted($ar_id[$i]))
                            $this->session->set_flashdata('message', 'Đã xóa thành công');
                        else
                            $this->session->set_flashdata('message', 'Xóa không thành công');
                    }
                }
            }
        }
        redirect('products/listproducts/' . $page);
    }

    function build_data($data, $flag = 1) {//flag=1:0?insert:update
        $dataUpdate["product_category_id"] = trim($data["product_category_id"]);
        $dataUpdate["name"] = trim($data["name"]);
        $dataUpdate["partners_id"] = trim($data["partners_id"]);
        $dataUpdate["code"] = trim($data["code"]);
        $dataUpdate["price"] = trim($data["price"]);
        $dataUpdate["sprice"] = trim($data["sprice"]);
        $dataUpdate["description"] = trim($data["description"]);
        $dataUpdate["features"] = trim($data["features"]);
        $dataUpdate["warranty"] = trim($data["warranty"]);
        $dataUpdate["details"] = trim($data["details"]);
        $dataUpdate["video"] = trim($data["video"]);
        $dataUpdate["style"] = trim($data["style_01"]) . ',' . trim($data["style_02"]) . ',' . trim($data["style_03"]);
        $dataUpdate["meta_tags"] = trim($data["meta_tags"]);
        $dataUpdate["nb_order"] = trim($data["nb_order"]);
        $dataUpdate["bl_active"] = trim($data["bl_active"]);
        $dataUpdate["soluong"] = trim($data["soluong"]);
        $dataUpdate["sku"] = trim($data["sku"]);
        $dataUpdate["home"] = trim($data["home"]);
        if ($flag == 1) {

            $dataUpdate["dt_create"] = date('Y-m-d H:i:s');
        }
        return $dataUpdate;
    }

}

?>
